package com.muxue.module.ai.config;

import com.muxue.common.utils.uuid.UUID;
import io.netty.channel.ChannelOption;
import io.netty.resolver.DefaultAddressResolverGroup;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;

@Slf4j
@Configuration
public class WebClientProvider {

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String baseUrl;

    @Value("${deepseek.api.timeout:30000}")
    private int timeout;

    @Resource
    private SecurityContextWebClientFilter securityContextWebClientFilter;


    public WebClient getClient(HttpServletRequest httpRequest) {
        HttpClient httpClient = HttpClient.create()
                .responseTimeout(Duration.ofSeconds(30))
                .resolver(DefaultAddressResolverGroup.INSTANCE) // 强制使用系统DNS解析器
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);

        return WebClient.builder()
                .baseUrl(baseUrl)
                .filter(securityContextWebClientFilter.securityContextFilter(httpRequest))
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .defaultHeader("Authorization", "Bearer " + apiKey)
                .defaultHeader("X-Request-ID", UUID.randomUUID().toString())
                .build();
    }



}